<template>
  <div>
    <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="1"
        :labelWidth="110"
        formType="add"
        :isSubmitBtn="false"
        @formChange="changeHandle"
      />

      <BreakSpace label="经销商角色类别选择" :containerStyle="{ marginBottom: '10px' }" />

      <FilterTable
        height="300"
        ref="dealerRoleTable"
        :columns="dealerRoleColumns"
        :dataSource="groupRoleList"
        :isSelectColumn="isSelectColumn"
        :datakey="'records'"
        :isToperInfo="false"
        :onColumnsChange="dealerRoleColumns => (this.dealerRoleColumns = dealerRoleColumns)"
        columnsRef="notification_maintain_info_02"
      >
        <template slot="controls">
          <el-button
            size="small"
            type="primary"
            icon="el-icon-plus"
            @click="dealerRoleHeader"
            :disabled="isOperator"
          >添加经销商角色类别</el-button>
        </template>
      </FilterTable>

    <!-- 角色选择弹窗 -->
    <BaseDialog
      title="经销商角色类别选择"
      :visible.sync="visibleDealerRole"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <dealer-role ref="addDealer" v-model="initDealerRoleData" @close="closeRoleDealer" />
    </BaseDialog>

      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="saveDialog" type="primary" :loading="saveLoading">保 存</el-button>
      </div>

  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import dealerRole from '@/pages/cms-pages/notification/maintain/dealerRole';
import { addOemRoleGroup ,updateOemRoleGroup} from '@/api/cms-api/notification/maintain/index';

export default {
  mixins: [dictionary],
  components: {
    dealerRole
  },
  props: {
    type: {
      type: String
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formList: this.createFormList(),
      dealerRoleColumns: this.creatHeader4DealerRoleColumns(),
      groupRoleList: [],
      initDealerRoleData: {},
      isSelectColumn: false,
      isOperator:  false, // 是否是详情
      visibleDealerRole: false,
      saveLoading:false,
      groupType:'',
      dataMain:null
    };
  },
  created() {
    this.init();
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '分组名称',
          fieldName: 'notificationGroupName',
          placeholder: '请输入...',
          maxlength:300,
          rules: [{ required: true,  trigger: 'blur',message: '请输入分组名称' }]
        }
      ]
    },
    creatHeader4DealerRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deleteDealerRole(props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '角色名称', dataIndex: 'text', sorter: true }
      ];
    },
    deleteDealerRole(index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.groupRoleList.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 角色选择窗口打开 -传数据
    dealerRoleHeader() {
      this.initDealerRoleData = {
        id: 1001
      }; //行id
      this.visibleDealerRole = true;
    },
    // 角色选择窗口 -返回数据
    closeRoleDealer(data) {
      //this.groupRoleList = data.data;
      this.addSelectRoleDealer(data.data);
      this.visibleDealerRole = data.visible; //关闭弹窗
    },
    //添加选择经销商角色到列表中
    addSelectRoleDealer(dealerRoles) {
      if (dealerRoles != null && typeof dealerRoles != 'undefined' && dealerRoles.length > 0) {
        dealerRoles.forEach(dealerRole => {
          let value = dealerRole.value;
          if (!this.isExistInlistRoleDealer(value)) {
            this.groupRoleList.push(dealerRole);
          }
        });
        this.groupRoleList.dataMark = false;
      }
    },
    isExistInlistRoleDealer(value) {
      let r = false;
      if (this.groupRoleList && this.groupRoleList.length > 0) {
        for (let dIdx = 0; dIdx < this.groupRoleList.length; dIdx++) {
          let tcode = this.groupRoleList[dIdx].value;
          if (tcode === value) {
            r = true;
            break;
          }
        }
      }
      return r;
    },
    //保存
    saveDialog() {
      this.groupType = '2';
      this.$refs.formPanel.SUBMIT_FORM();
    },
    changeHandle(data) {
      this.dataMain = data;
      this.submit();
    },
    // 保存
    async submit() {
      var flag = this.packageData();
      if (flag === -1) {
        return;
      }
      this.saveLoading = true;
      console.log(this.dataMain)
      if(this.type == 'edit'){
        this.dataMain.notificationGroupId = this.rowData.notificationGroupId;
        this.validReturnDate(await updateOemRoleGroup(this.dataMain));
      }else{
        this.validReturnDate(await addOemRoleGroup(this.dataMain));
      }
    },
    validReturnDate(res) {
      if (res.resultCode === 200) {
        this.saveLoading = false;
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.saveLoading = false;
        this.$notify.error({ title: '提示信息', message: res.errMsg || '操作失败!' });
      }
    },
    // 数据组装
    packageData() {
      this.packagegroupRoleList();
      this.dataMain.notificationGroupType = this.groupType;
    },
    // 封装经销商角色类别信息
    packagegroupRoleList() {
      var temp = [];
      for (var i = 0; i < this.groupRoleList.length; i++) {
        var body = {};
        body.codeCnDesc = this.groupRoleList[i].text;
        body.codeId = this.groupRoleList[i].value;
        body.type = 2;
        temp.push(body);
      }
      this.dataMain.groupRoleList = temp;
    },
    closeDialog(type) {
      this.$emit('close', false, type);
    },
    init() {
      if (this.type === 'edit') {
        this.formList.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
        });

      let rows = [];
      if(this.rowData.roleId != null){
        if (this.rowData.roleId.indexOf(',')  != -1) {
          let roleIds = this.rowData.roleId.split(',');
          let roleNames = this.rowData.roleName.split(',');
          for (let y = 0 ;y < roleIds.length ; y++) {
              let data = {}
              data.value = parseInt(roleIds[y]);
              data.text  =  roleNames[y];
              rows.push(data);
            }
        }else{
          let data2 = {}
          data2.value = parseInt(this.rowData.roleId);
          data2.text  =  this.rowData.roleName;
          rows.push(data2);
        }
      }
      this.addSelectRoleDealer(rows);
       }
    },
  }
};
</script>

<style lang="less" scoped>
</style>
